<?php

namespace PKApp\Area;

use PKApp\Area\Classes\TraitArea;
use PKCommon\Controller\AdminController;
use PKFrame\DataHandler\Arrays;

class AdminGetArea extends AdminController
{
    use TraitArea;

    public function Main()
    {
        $this->callOfSellFunc();
        $this->fetch('list_area');
    }

    protected function getListOfArea()
    {
        $this->json($this->serviceOfArea()->GetList());
    }

    protected function getTreeOfArea()
    {
        $this->json(
            $this->_treeCategoryList(
                $this->serviceOfArea()->GetList(), 0
            )
        );
    }

    private function _treeCategoryList($entityList, $parentCode = null): array
    {
        $result = [];
        $nowChild = array_filter($entityList, function ($entity) use ($parentCode) {
            return $entity['parentCode'] == $parentCode ? $entity : [];
        });
        if (Arrays::Is($nowChild)) {
            $action = request()->action();
            foreach ($nowChild as $item) {
                $children = $this->_treeCategoryList($entityList, $item['id']);
                $tmp = ['name' => $item['name'], 'value' => $item['code']];
                !Arrays::Is($children) ?: $tmp['children'] = $children;
                $result[] = $tmp;
            }
        }
        return $result;
    }

}